package com.lwtek.demo;

import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.lwtek.demo.databinding.ActivityDeviceBinding;
import com.lwtek.scanner.core.ScannerDevice;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author kvery
 * @date 2023-05-04 19:33
 */
public class DeviceActivity extends AppCompatActivity {

    private ActivityDeviceBinding binding;

    private ScannerDevice device;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDeviceBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        device = MyApplication.getDevice();

        TextView dataView = binding.dataView;
        dataView.setMovementMethod(ScrollingMovementMethod.getInstance());

        Button sendBtn = binding.sendBtn;

        sendBtn.setOnClickListener(v -> {
            // `send(bytes)` sends a command, such as `ba0515`, which returns battery information. This is case-insensitive.
            String command = binding.editText.getText().toString();
            int length = command.length();
            if (length % 2 == 0) {
                byte[] bytes = new byte[length / 2];
                for (int i = 0; i < length; i++) {
                    if (i % 2 == 0) {
                        bytes[i / 2] = (byte) Integer.parseInt(command.substring(i, i + 2), 16);
                    }
                }
                device.send(bytes);
            }
        });
        // `onData` is the data being monitored from the scanner device, `bytes` is a byte array, and `str` is the converted string.
        device.onData(
                (bytes, str) -> runOnUiThread(() -> {
                    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
                    dataView.append(formatter.format(new Date()) + "> " + str + "\n");
                    int offset = (dataView.getLineCount() + 1) * dataView.getLineHeight();
                    if (offset > dataView.getHeight()) {
                        dataView.scrollTo(0, offset - dataView.getHeight());
                    }
                })
        );
    }
}